// app.js
import { request } from './request/index.js';
App({
  getOpenIdCount: 0,
  getUserInfoCount: 0,

  async onShow() {
    await this.getUserInfo();
  },
  onLaunch() {

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })

  },

  // 获取openId
  async getOpenId() {
    try {
      const o = wx.getStorageSync('openId')
      if (o) {
        return o
      }
      const self = this
      const { code } = await wx.login()
      const { data } = await request({
        url: '/UserInfo/getCode',
        data: { code },
      })
      if (!data && this.getOpenIdCount <= 10) {
        self.getOpenIdCount++
        await self.getOpenId()
      } else {
        wx.setStorageSync('openId', data)
        return Promise.resolve(data)
      }

    } catch (error) {
      console.log(error)
    }
  },


  async getUserInfo() {
    try {
      const self = this
      const { data } = await request({
        url: '/UserInfo/getUserByOpenId',
        data: { openid: await this.getOpenId() },
      })
      if (!data && self.getUserInfoCount <= 10) {
        self.getUserInfoCount++
        await this.loginUserPhone('');
        await this.getUserInfo();
      } else {
        wx.setStorageSync('user', data)
        this.globalData.userId = data.userId
      }
    } catch (error) {
      console.log(error)
    }

  },
  async loginUserPhone(phone) {
    try {
      const { data } = await request({
        url: '/UserInfo/addUserInfo',
        data: { userPhone1: phone, openid: await this.getOpenId() },
      })
    } catch (error) {
      console.log(error)
    }
  },
  async goLoginPub(phoneCode) {
    try {
      if (!phoneCode) return
      const { code, data } = await request({
        url: "/UserInfo/getPhoneNumber",
        data: { code: phoneCode },
      })
      if (data) {
        console.log("登录信息：", data)
        wx.setStorageSync('accessToken', data)
        await this.loginUserPhone(data)
        await this.getUserInfo()
        return Promise.resolve(true)
      } else {
        return Promise.resolve(false)
      }
    } catch (error) {
      throw error;
      console.log('error :>> ', error);
    }
  },
  globalData: {
    userId: "-1"
  }
})
